#!/bin/bash
mariadb=$(rpm -qa|grep mariadb)
if [[ $mariadb ]];then
    echo "卸载$mariadb"
    rpm -e --nodeps $mariadb
fi
mysqlfile=$(ls -l |grep mysql*tar.gz | awk '{print $9}')
echo "正在解压：$mysqlfile"
tar -zxvf $mysqlfile
echo "解压完毕！"
mysqldir=${mysqlfile%%.tar.gz}
mv $mysqldir mysql
echo "请设置安装路径(默认/usr/local/)："
basepath="/usr/local"
read install_path
if [[ $install_path ]];then
    basepath=$install_path
fi
mkdir -p $basepath
mv mysql $basepath
basepath=$basepath/mysql
hasgroup=$(cat /etc/group|grep mysql)
if [[ ! $hasgroup ]];then
    echo "创建mysql用户组"
    groupadd mysql
fi
hasuser=$(cat /etc/passwd|grep mysql)
if [[ ! $hasuser ]];then
    echo "创建mysql用户"
    useradd -g mysql mysql
    echo "请为mysql用户设置密码："
    passwd mysql
fi
chown -R mysql:mysql $basepath
#touch /etc/my.cnf
echo "" > /etc/my.cnf
echo "[mysqld]" >> /etc/my.cnf
echo "sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" >> /etc/my.cnf
echo "default-time_zone = '+8:00'" >> /etc/my.cnf
echo "请设置mysql端口："
read mysql_port
echo "port = $mysql_port" >> /etc/my.cnf
echo "socket=/var/lib/mysql/mysql.sock" >> /etc/my.cnf
echo "basedir=$basepath" >> /etc/my.cnf
echo "datadir=$basepath/data" >> /etc/my.cnf
echo "log-error = $basepath/data/error.log" >> /etc/my.cnf
echo "pid-file = $basepath/data/mysql.pid" >> /etc/my.cnf
echo "tmpdir = /tmp/mysql" >> /etc/my.cnf
echo "max_connections=200" >> /etc/my.cnf
echo "character-set-server=utf8" >> /etc/my.cnf
echo "default-storage-engine=INNODB" >> /etc/my.cnf
echo "lower_case_table_names=1" >> /etc/my.cnf
echo "max_allowed_packet=16M" >> /etc/my.cnf
echo "user=mysql" >> /etc/my.cnf
chown -R mysql:mysql /etc/my.cnf
mkdir -p /var/lib/mysql
mkdir -p /tmp/mysql
mkdir -p $basepath/data
chown -R mysql:mysql /var/lib/mysql
chown -R mysql:mysql $basepath
chown -R mysql:mysql /tmp/mysql
echo "正在安装中..."
$basepath/bin/mysqld --initialize --user=mysql
cp $basepath/support-files/mysql.server /etc/rc.d/init.d/mysqld
chmod +x /etc/rc.d/init.d/mysqld
chkconfig --add mysqld
chkconfig --list mysqld
service mysqld start
echo "查看初始化的mysql密码："
cat $basepath/data/error.log | grep password
echo "export PATH=$PATH:$basepath/bin" >> /etc/profile
source /etc/profile
ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock
mysql -u root -p
